package cn.itcast.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.itcast.nio.c2.ByteBufferUtil.debugAll;

/**
 *
 */
public class MultipleServer {

    public static void main(String[] args) throws IOException {
        new BossEventLoop().register();
    }



    @Slf4j
    static class BossEventLoop implements Runnable {

        private Selector boss;
        private WorkerEventLoop[] workers;
        private AtomicInteger index = new AtomicInteger();
        private volatile boolean start = true;

        private void register() throws IOException {
            if (start) {
                boss = Selector.open();
                ServerSocketChannel ssc = ServerSocketChannel.open();
                ssc.configureBlocking(false);
                SelectionKey sscKey = ssc.register(boss, 0, null);
                sscKey.interestOps(SelectionKey.OP_ACCEPT);
                ssc.bind(new InetSocketAddress(9090));
                workers = initEventLoop();
                new Thread(this, "boss").start();
                log.debug("Boss start ...");
                start = false;
            }
        }

        private WorkerEventLoop[] initEventLoop() {
            WorkerEventLoop[] workerEventLoops = new WorkerEventLoop[2];
            for (int i = 0; i < workerEventLoops.length; i++) {
                workerEventLoops[i] = new WorkerEventLoop(i);
            }
            return workerEventLoops;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    boss.select();
                    Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
                    if (iterator.hasNext()) {
                        SelectionKey sscKey = iterator.next();
                        iterator.remove();
                        if (sscKey.isAcceptable()) {
                            ServerSocketChannel ssc = (ServerSocketChannel) sscKey.channel();
                            SocketChannel sc = ssc.accept();
                            log.debug("{} connected", sc.getRemoteAddress());
                            sc.configureBlocking(false);
                            workers[index.getAndIncrement() % workers.length].register(sc);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Slf4j
    static class WorkerEventLoop implements Runnable {

        private int index;
        private Selector selector;
        private volatile boolean start = true;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue();

        public WorkerEventLoop(int index) {
            this.index = index;
        }

        public void register(SocketChannel sc) throws IOException {
            if (start) {
                selector = Selector.open();
                new Thread(this, "worker-" + index).start();
                start = false;
            }
            queue.add(() -> {
                try {
                    SelectionKey scKey = sc.register(selector, 0, null);
                    scKey.interestOps(SelectionKey.OP_READ);
                    selector.selectNow();
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            selector.wakeup();
        }

        @Override
        public void run() {
            while (true) {
                try {
                    selector.select();
                    Runnable task = queue.poll();
                    if (task != null) {
                        task.run();
                    }
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey scKey = iterator.next();
                        if (scKey.isReadable()) {
                            SocketChannel sc = (SocketChannel) scKey.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(128);
                            try {
                                int read = sc.read(buffer);
                                if (read == -1) {
                                    scKey.cancel();
                                    sc.close();
                                } else {
                                    buffer.flip();
                                    log.debug("{} message:", sc.getRemoteAddress());
                                    debugAll(buffer);
                                }
                            } catch (IOException e) {
                                scKey.cancel();
                                sc.close();
                                e.printStackTrace();
                            }

                        }

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
